package cn.wk.libs4a.utils;

import java.lang.reflect.Type;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.Html;
import cn.wk.libs4a.WKApplication;
import cn.wk.libs4a.WKBaseActivity;
import cn.wk.libs4a.bean.VersionBean;
import cn.wk.libs4a.net.WKAsyncTask;
import cn.wk.libs4a.net.WKAsyncTaskPro;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

/**
 * 检查更新
 * 
 * 注意：
 * 
 * 1 版本比较的是version_code，四位数
 * 
 * 2 Bean格式必须包含VersionBean。
 * 
 * 用法：
 * 
 * WKCheckAppUpdate.getInstance().check(this, new GetDataForUpdate() { public
 * String getData() { return app().net.get_version(); } });
 */
public class WKCheckAppUpdate {

	private WKBaseActivity activity;

	private CheckAppUpdateBack checkBack;
	private GetDataForUpdate getData;

	private static WKCheckAppUpdate checkAppUpdate;

	public static WKCheckAppUpdate getInstance() {
		if (checkAppUpdate == null) {
			checkAppUpdate = new WKCheckAppUpdate();
		}
		return checkAppUpdate;
	}

	/**
	 * 是否是手动点击的检测，用来判断，是否给提示信息
	 */
	public boolean clickCheck = false;

	/**
	 * 点击检测，带提示，需传数据
	 */
	public void check(WKBaseActivity act, GetDataForUpdate getData) {
		clickCheck = false;
		this.activity = act;
		this.getData = getData;
		new CheckAppUpdateTask(activity).execute();
	}

	/**
	 * 点击检测，带提示，需传数据
	 */
	public void clickCheck(WKBaseActivity act, GetDataForUpdate getData) {
		clickCheck = true;
		this.activity = act;
		this.getData = getData;
		new CheckAppUpdateTask(activity).execute();
	}

	/**
	 * 设置检测类，监听状态用的
	 */
	public void setCheckUpdateback(CheckAppUpdateBack back) {
		this.checkBack = back;
	}

	/****************************************************************
	 * 接口
	 */
	class CheckAppUpdateTask extends WKAsyncTask<String, String, String> {
		public CheckAppUpdateTask(Context context) {
			super(context);
		}

		protected void doOnPostExecute(String result) {
//			dealWithString(result);
			checkBack.checkBack(result);
		}

		@Override
		protected String doInBackground(String... params) {
			return getData.getData();
		}
	}

	/**
	 * 广告页
	 */
	class GetAdListTask extends WKAsyncTaskPro {

		public GetAdListTask(Context context) {
			super(context);
		}

		protected void doOnPostExecute(String result, boolean isLocal) {
			dealWithString(result);
		}

		protected String doInBackground(boolean... isLocal) {
			return getData.getData();
		}
	}

	private void dealWithString(String result) {
		VersionBean bean = new VersionBean();
		JSONObject o = null;
		try {
			o = new JSONObject(result).getJSONObject("data");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		bean.version = o.optString("version");
		bean.url = o.optString("url");
		bean.info = o.optString("info");
		dealWithBean(bean);
	}

	/**
	 * 处理返回
	 */
	private void dealWithBean(VersionBean bean) {

		try {
			String verStr = bean.version;
			int ver = Integer.valueOf(verStr.replace(".", ""));
			int curVer = WKUtils.getVersionCode(activity);

			// 需要将结果返回
			if (checkBack != null) {
//				checkBack.checkBack(ver - curVer);
			}
			// 最新
			if (curVer >= ver) {
				// 点击更新按钮，需要给提示
				if (clickCheck) {
					AlertDialog.Builder builder = new Builder(activity);
					builder.setTitle("更新提示");
					builder.setMessage("已经是最新版本了! ");
					builder.show();
				}
			} else if (ver - curVer > 0) {// 需要更新
				if (bean.url.endsWith(".apk")) {
					showDownloadDialog(bean.url, bean.info);
				} else {
					// 点击更新按钮，需要给提示
					if (clickCheck) {
						WKApplication.showToast("下载地址不正确:" + bean.url);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			WKApplication.showToast("服务器异常");
		}
	}

	/**
	 * 弹出提示下载对话框
	 */
	public void showDownloadDialog(final String downloadUrl, String msg) {
		AlertDialog.Builder builder = new Builder(activity);
		builder.setTitle("提示");
		builder.setMessage(Html.fromHtml(msg));
		builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Uri uri = Uri.parse(downloadUrl);
						Intent intent = new Intent(Intent.ACTION_VIEW, uri);
						activity.startActivity(intent);
						dialog.dismiss();
					}
				});
		builder.setNeutralButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	/**
	 * 弹出提示下载对话框，是否强制更新
	 */
	public void showDownloadDialog(final Context mContext,
			final String downloadUrl, String msg, final boolean force) {
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("提示");
		if (force) {
			builder.setCancelable(false);
		}
		builder.setMessage(Html.fromHtml(msg));
		builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Uri uri = Uri.parse(downloadUrl);
						Intent intent = new Intent(Intent.ACTION_VIEW, uri);
						mContext.startActivity(intent);
						dialog.dismiss();
						if (force) {
							((Activity) activity).finish();
						}
					}
				});
		if (force == false) {
			builder.setNeutralButton("取消",
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
		}
		builder.create().show();
	}

	/**
	 * 检测更新返回
	 */
	public interface CheckAppUpdateBack {
		/**
		 * 返回数据。
		 * @param result
		 */
		public void checkBack(String result);
	}

	/**
	 * 获取数据
	 */
	public interface GetDataForUpdate {
		public String getData();
	}

}
